﻿using Nancy.Hosting.Self;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace NancyDemo
{
    class Program
    {
        static void Main(string[] args)
        {

           
            int httpPort = 9880;
            int httpsPort = 9980;
            string ip = "localhost";
            string httpsAddress = $"https://{ip}:{httpsPort}/";
            string httpAddress = $"http://{ip}:{httpPort}/";


            var config = new HostConfiguration()
            {
                UrlReservations = new UrlReservations() { CreateAutomatically = false },
                RewriteLocalhost = true, 
                EnableClientCertificates = false
            };


             
            using (var host = new NancyHost(config,new Uri(httpAddress), new Uri(httpsAddress)))
            {

                //删除已注册对应地址端口的ssl证书
                runCmd($"netsh http delete sslcert ipport=0.0.0.0:{httpPort}");
                runCmd($"netsh http delete sslcert ipport=[::]:{httpPort}");
                runCmd($"netsh http delete sslcert ipport=0.0.0.0:{httpsPort}");
                runCmd($"netsh http delete sslcert ipport=[::]:{httpsPort}");

                //删除已注册对应地址端口的url
                runCmd($"netsh http delete urlacl url=https://+:{httpsPort}/");
                runCmd($"netsh http delete urlacl url=https://localhost:{httpsPort}/");
                runCmd($"netsh http delete urlacl url=http://+:{httpsPort}/");
                runCmd($"netsh http delete urlacl url=http://localhost:{httpsPort}/");

                //注册ssl证书certhash=be8f57d67a42ec20df6824eb2926d01341eb1ca1对应证书指纹
                //runCmd($"netsh http add sslcert ipport=0.0.0.0:{httpsPort} certhash=be8f57d67a42ec20df6824eb2926d01341eb1ca1" + " appid={C5543231-5487-488E-8B09-0B80BA4FEEF7}");
                runCmd($"netsh http add sslcert ipport=0.0.0.0:{httpsPort} certhash=be8f57d67a42ec20df6824eb2926d01341eb1ca1 appid={{{Assembly.GetEntryAssembly().GetCustomAttribute<GuidAttribute>().Value}}}");

                host.Start(); 

                Console.WriteLine("按任意键退出");
                Console.ReadKey();
                host.Stop();
            }

           

        }

        private static void runCmd(string cmdStr) {

            Process process = new Process();
            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            processStartInfo.FileName = "cmd.exe";
            //processStartInfo.Arguments = $"/C netsh http delete urlacl url=\"https://+:{port}/\"  &&  netsh http add urlacl url=\"https://+:{port}/\" user=\"Everyone\"";
            processStartInfo.Arguments = $"/C {cmdStr}";
            processStartInfo.Verb = "runas";
            process.StartInfo = processStartInfo;
            process.Start();

        }
    }
}
